package com.pussinboots.morning.cms.modules.upload.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.pussinboots.morning.cms.modules.system.product.entity.OsProductImage;
import com.pussinboots.morning.cms.modules.system.product.service.IOsProductImageService;
import com.pussinboots.morning.common.controller.BaseController;
import com.pussinboots.morning.common.result.ResponseResult;

@Controller
@RequestMapping(value="/uploads")
public class ImageUploadController extends BaseController{
	
	private static final Logger logger = LoggerFactory.getLogger(ImageUploadController.class);
	
	private String allowSuffix = "jpg,png,gif,jpeg";
	private long allowSize = 2 *1024*1024;
	
	@Autowired
	private IOsProductImageService osProductImageServiceImpl;
	
	
	/**
	 * POST 商品图片上传
	 * @param avatar_file
	 * @param avatar_src
	 * @param avatar_data
	 * @return
	 */
	@ResponseBody
	@PostMapping(value = "/uploadGoodsPic", produces = "application/json;charset=utf-8")
	public ResponseResult uploadGoodsPic(MultipartFile[] file, HttpServletRequest request,HttpServletResponse response) {
		
		//String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
		
		if(file!=null && file.length > 0){
			try {
			    String path = getPicPath();
				String[] fileName =  uploads(file, path,request);
				
				//存储图片路径
				List<OsProductImage> entityList = new ArrayList<OsProductImage>();
				for(String name : fileName){
					OsProductImage image = new OsProductImage();
					image.setCreateBy("张三");
					Date createTime = new Date();
					image.setCreateTime(createTime);
					image.setPicImg(name);
					image.setProductId(1l);
					image.setStatus(1);
					image.setSort(1);
					entityList.add(image);
				}
				osProductImageServiceImpl.insertBatch(entityList);
				
				
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return fail(false, "图片不存在,请确认图片地址重新上传!");
	}
	

	/**
	 * 
	 * <p class="detail">
	 * 功能：重新命名文件
	 * </p>
	 * @author wangsheng
	 * @date 2014年9月25日 
	 * @return
	 */
	private String getFileNameNew(){
		SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS");
		return fmt.format(new Date());
	}
	
	/**
	 * 
	 * @return
	 */
	private String getPicPath() {
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
		String dateString = formatter.format(currentTime);
		String path = "images/goods/" + dateString +"/";
		return path;
	}
	
	/**
	 * 
	 * <p class="detail">
	 * 功能：文件上传
	 * </p>
	 * @author wangsheng
	 * @date 2014年9月25日 
	 * @param files
	 * @param destDir
	 * @throws Exception
	 */
	public String[] uploads(MultipartFile[] files, String destDir, HttpServletRequest request) throws Exception {
		String[] fileNames = new String[files.length];
		try {
			for (int i=0;i<files.length;i++) {
				MultipartFile file = files[i];
				String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
				int length = allowSuffix.indexOf(suffix);
				if (length == -1) {
					throw new Exception("请上传允许格式的文件");
				}
				if (file.getSize() > allowSize) {
					throw new Exception("您上传的文件大小已经超出范围");
				}
				String realPath = request.getSession().getServletContext().getRealPath("/");
				File destFile = new File(realPath + "uploads/" + destDir);
				if (!destFile.exists()) {
					destFile.mkdirs();
				}
				String fileNameNew = getFileNameNew() + "." + suffix;
				File f = new File(destFile.getAbsoluteFile() + "\\" + fileNameNew);
				file.transferTo(f);
				f.createNewFile();
				fileNames[i] = destDir + fileNameNew;
			}
		} catch (Exception e) {
			throw e;
		}
		
		return fileNames;
	}
	
	/**
	 * 
	 * <p class="detail">
	 * 功能：文件上传
	 * </p>
	 * @author wangsheng
	 * @date 2014年9月25日 
	 * @param files
	 * @param destDir
	 * @throws Exception
	 */
	public String upload(MultipartFile file, String destDir, HttpServletRequest request) throws Exception {
		String fileName = "";
		try {
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
			int length = allowSuffix.indexOf(suffix);
			if (length == -1) {
				throw new Exception("请上传允许格式的文件");
			}
			if (file.getSize() > allowSize) {
				throw new Exception("您上传的文件大小已经超出范围");
			}
			//获取图片路径
			String realPath = request.getSession().getServletContext().getRealPath("/");
			File destFile = new File(realPath + "uploads/" + destDir);
			//如果路径不存在，创建路径
			if (!destFile.exists()) {
				destFile.mkdirs();
			}
			//创建文件名称
			String name = getFileNameNew() + "." + suffix;
			String rPath = destFile.getAbsoluteFile() + "/" + name;
			//创建文件
			File f = new File(rPath);
			file.transferTo(f);
			f.createNewFile();
			fileName = destDir + name;
			
		} catch (Exception e) {
			throw e;
		}
		return fileName;
	}
}
